package com.birdboot.controller;

import com.birdboot.entity.User;
import com.birdboot.http.HttpServletRequest;
import com.birdboot.http.HttpServletResponse;

import java.io.*;

public class UserController {
    public static File userDir;
    static {
        userDir = new File("./users");
        if (!userDir.exists()){
            userDir.mkdirs();
        }
    }
    public void reg(HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println("开始处理用户注册！！！");
        // 1、通过表单获取数据
        String username = request.getParameters("username");
        String password = request.getParameters("password");
        String nickname = request.getParameters("nickname");
        String ageStr = request.getParameters("age");
        System.out.println(username+","+password+","+nickname+","+ageStr);
        // 必要验证
        if (username==null||username.isEmpty()||
            password==null||password.isEmpty()||
            nickname==null||nickname.isEmpty()||
            !ageStr.matches("[0-9]+")){
            // 重定向注册失败页面
            response.sentRedirect("/reg_info_error.html");
            return;
        }
        File file = new File(userDir,username+".obj");
        if (file.exists()){
            response.sentRedirect("/have_user.html");
            return;
        }
        int age = Integer.parseInt(ageStr);
        User user = new User(username,password,nickname,age);
        try (
                FileOutputStream fos = new FileOutputStream(file);
                ObjectOutputStream oos = new ObjectOutputStream(fos);
                ){
            oos.writeObject(user);
            response.sentRedirect("/reg_success.html");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void login(HttpServletRequest request,HttpServletResponse response) throws IOException {
        System.out.println("开始处理用户登录！！！");
        String username = request.getParameters("username");
        String password = request.getParameters("password");
        System.out.println(username+","+password);
        if (username == null || username.isEmpty()||
            password == null || password.isEmpty()){
            response.sentRedirect("/login_info_error.html");
            return;
        }
        File file = new File(userDir,username+".obj");
        if (file.exists()){
            try(
                    FileInputStream fis = new FileInputStream(file);
                    ObjectInputStream ois = new ObjectInputStream(fis);
                    ){
                User user = (User) ois.readObject();
                if (user.getPassword().equals(password)){
                    response.sentRedirect("/login_success.html");
                    return;
                }

            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
        response.sentRedirect("/login_fail.html");


    }
}
